﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using StaffWarsFm.Lib.Data;
using StaffWarsFm.Questions;
using StaffWarsFm.Server;

namespace StaffWarsFm.Services
{
    public class Challenge
    {
        private ClientReference challenger;
        private readonly ClientReference radioMaster;
        private readonly IEnumerable<User> allUsers;
        private bool? challengerAnswerCorrect;
        private bool? radioMasterAnswerCorrect;
        
        public Challenge(ClientReference challenger, ClientReference radioMaster, IEnumerable<User> allUsers)
        {
            this.challenger = challenger;
            this.radioMaster = radioMaster;
            this.allUsers = allUsers;

            StartQuestionGeneration();
        }

        public void StartQuestionGeneration()
        {
            Question = null;
            new Thread(GenerateQuestion).Start();
        }

        public Question Question { get; private set; }

        public ClientReference Challenger
        {
            get { return challenger; }
        }

        private void GenerateQuestion()
        {
            var questionService = new DemoQuestionService();

            var players = new[] {challenger.User, radioMaster.User};
            var connectedUsers = allUsers.ToArray();

            Thread.Sleep(3000);
            
            while (Question == null)
            {
                try
                {
                    Question = questionService.GenerateQuestion(players, connectedUsers);
                }
                catch (Exception)
                {
                    Debug.WriteLine("Failed to generate question.");
                }
            }

            radioMasterAnswerCorrect = null;
            challengerAnswerCorrect = null;

            OnQuestionGenerated(EventArgs.Empty);
        }

        private Question GenerateTestQuestion()
        {
            return new Question
            {
                Text =
                    "This is a really long question which should hopefully cause the text block to overflow correctly?",
                ImageUrl = "http://userserve-ak.last.fm/serve/252/190252.jpg",
                Answers = new[]
                            {
                                new Answer
                                    {
                                        Text = "Answer 1",
                                        ImageUrl = "http://userserve-ak.last.fm/serve/174s/8606131.jpg",
                                        IsCorrect = true
                                    },
                                new Answer
                                    {
                                        Text = "Answer 2",
                                        ImageUrl = null,
                                        IsCorrect = false
                                    },
                                new Answer
                                    {
                                        Text = "Answer 3",
                                        ImageUrl = "http://userserve-ak.last.fm/serve/174s/8606131.jpg",
                                        IsCorrect = false
                                    },
                                new Answer
                                    {
                                        Text = "Answer 4",
                                        ImageUrl = "http://userserve-ak.last.fm/serve/174s/8606131.jpg",
                                        IsCorrect = false
                                    },
                            }
            };
        }

        public ChallengeResult SubmitAnswer(ClientReference clientReference, bool wasCorrect)
        {
            if (clientReference == radioMaster)
                radioMasterAnswerCorrect = wasCorrect;

            if (clientReference == challenger)
                challengerAnswerCorrect = wasCorrect;

            if (radioMasterAnswerCorrect != null && challengerAnswerCorrect != null)
            {
                ClientReference winner = null;

                if (radioMasterAnswerCorrect.Value != challengerAnswerCorrect.Value)
                    winner = radioMasterAnswerCorrect.Value ? radioMaster : challenger;

                return new ChallengeResult {Complete = true, Winner = winner};
            }

            return new ChallengeResult {Complete = false};
        }

        public event EventHandler<EventArgs> QuestionGenerated;

        protected virtual void OnQuestionGenerated(EventArgs e)
        {
            var handler = QuestionGenerated;

            if (handler != null)
                handler(this, e);
        }
    }
}
